import 'dart:math';

import 'package:chat_ai/src/views/chat_view.dart';
import 'package:chat_ai/src/views/create_session.dart';
import 'package:chat_ai/src/views/session_config.dart';
import 'package:flutter/material.dart';
import 'package:glassmorphism_widgets/glassmorphism_widgets.dart';
import 'package:mesh_gradient/mesh_gradient.dart';

import 'package:shared_preferences/shared_preferences.dart';

import 'package:chat_ai/src/models/session_model.dart';

class SessionList extends StatefulWidget {
  const SessionList({super.key});

  @override
  State<SessionList> createState() => _SessionListState();
}

class _SessionListState extends State<SessionList> {
  List<SessionModel> sessionModelList = [];

  @override
  void initState() {
    super.initState();
    _loadSessions();
  }

  Future<void> _loadSessions() async {
    sessionModelList = [];
    final prefs = await SharedPreferences.getInstance();
    List<String> sessionNames = prefs.getStringList("sessionNames") ?? [];
    setState(() {
      for (String name in sessionNames) {
        String? host = prefs.getString("$name.host");
        if (host == null) continue;
        int? port = prefs.getInt("$name.port");
        if (port == null) continue;
        sessionModelList.add(SessionModel(name: name, host: host, port: port));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned.fill(
          child: AnimatedMeshGradient(
            colors: const [
              // Color.fromARGB(255, 255, 128, 143),
              Color.fromARGB(255, 138, 224, 255),
              Color.fromARGB(255, 246, 255, 169),
              Color.fromARGB(255, 153, 255, 74),
              Color.fromARGB(255, 255, 185, 209),
            ],
            options: AnimatedMeshGradientOptions(speed: 10),
          ),
        ),
        Scaffold(
          backgroundColor: Colors.transparent,
          appBar: const GlassAppBar(
            title: GlassText(
              "首页",
              style: TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
              ),
            ),
            blur: 200.0,
            border: 0,
          ),
          body: Padding(
            padding: const EdgeInsets.all(12),
            child: GridView.count(
              crossAxisCount: max(
                MediaQuery.of(context).size.width.toInt() ~/ 200,
                1,
              ),
              children: sessionModelList
                  .map(
                    (session) => Padding(
                      padding: const EdgeInsets.all(4.0),
                      child: GlassContainer(
                        blur: 80,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(14.0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    session.name,
                                    style:
                                        Theme.of(context).textTheme.titleMedium,
                                  ),
                                  const Divider(
                                    thickness: 0,
                                    color: Colors.white,
                                  ),
                                  Text.rich(
                                    TextSpan(
                                      children: [
                                        const TextSpan(
                                          text: "IP地址：",
                                          style: TextStyle(
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        TextSpan(
                                          text: session.host,
                                        ),
                                      ],
                                    ),
                                  ),
                                  Text.rich(
                                    TextSpan(
                                      children: [
                                        const TextSpan(
                                          text: "端口号：",
                                          style: TextStyle(
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        TextSpan(
                                          text: "${session.port}",
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Row(
                              children: [
                                Expanded(
                                  child: OutlinedButton(
                                    style: OutlinedButton.styleFrom(
                                      backgroundColor: Colors.transparent,
                                      side: const BorderSide(
                                        color: Colors.white,
                                      ),
                                      shape: const RoundedRectangleBorder(
                                        borderRadius: BorderRadius.zero,
                                      ),
                                      shadowColor: Colors.transparent,
                                    ),
                                    onPressed: () async {
                                      await Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) => ChatView(
                                            sessionModel: session,
                                          ),
                                        ),
                                      );
                                    },
                                    child: const Text(
                                      "进入",
                                      style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: OutlinedButton(
                                    style: OutlinedButton.styleFrom(
                                      backgroundColor: Colors.transparent,
                                      side: const BorderSide(
                                        color: Colors.white,
                                      ),
                                      shape: const RoundedRectangleBorder(
                                        borderRadius: BorderRadius.zero,
                                      ),
                                      shadowColor: Colors.transparent,
                                    ),
                                    onPressed: () async {
                                      await Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) => SessionConfig(
                                            sessionModel: session,
                                          ),
                                        ),
                                      );
                                      _loadSessions();
                                      setState(() {});
                                    },
                                    child: const Text(
                                      "设置",
                                      style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                  )
                  .toList(),
            ),
          ),
          bottomNavigationBar: BottomAppBar(
            color: Colors.transparent,
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.transparent,
              ),
              onPressed: () async {
                await Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const CreateSession(),
                  ),
                );
                await _loadSessions();
                setState(() {});
              },
              child: const Text("新建会话"),
            ),
          ),
        ),
      ],
    );
  }
}
